package com.example.test.support;


import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.example.test.qtnet.BaseResponseBean;
import com.example.test.qtnet.RequestHead;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * 网络接口基类
 */
public class QiantoonNetworkApi extends BaseNetworkApi {
    public static final String URL = "http://%s:%s/QiantoonService/";
    protected static volatile QiantoonNetworkApi sInstance;


    public static <T> T getService(Class<T> service) {
        return getInstance().getRetrofit(service).create(service);
    }

    public static QiantoonNetworkApi getInstance() {
        if (sInstance == null) {
            synchronized (QiantoonNetworkApi.class) {
                if (sInstance == null) {
                    sInstance = new QiantoonNetworkApi();
                }
            }
        }
        return sInstance;
    }

    /*** 获取公共参数 */
    public Map<String, String> getCommonParameter() {
        Map<String, String> dataMap = new HashMap<>();
        Map<String, String> userInfo = PreferencesUtil.getInstance().getUserInfo(Map.class);
        if (userInfo != null) {
            dataMap.put("UserToken", userInfo.get("Token"));
            dataMap.put("OperID", userInfo.get("OperID"));
            dataMap.put("HealthyCardID", userInfo.get("HealthyCardID"));
        }
        dataMap.put("SystemType", "Android");//系统平台类型，Android,IOS
        dataMap.put("DeviceId", DeviceUtils.getUniqueDeviceId());//唯一设备号
        return dataMap;
    }

    public static String ToastStr_105 = "您的账号在其他设备登录，请重新登录";

    @Override
    protected Interceptor getRequestInterceptor() {
        return chain -> {
            Request request = chain.request();

            if (!TextUtils.isEmpty(getAuth_token())) {
                Map<String, Object> requestMap = new HashMap<>();
                String timeStamp = QianToonApiUtil.getTimeStamp();

                Map<String, String> partFileMap = null;

                requestMap.put("head", new RequestHead(getAuth_token(), QianToonApiUtil.HEAD_KEY, timeStamp));
                if (request.body() instanceof FormBody) {
                    FormBody formBody = (FormBody) request.body();
                    int paramsSize = formBody.size();
                    if (paramsSize > 0) {
                        Map<String, String> dataMap = new HashMap<>();
                        for (int i = 0; i < paramsSize; i++) {
                            String name = formBody.name(i);
                            if (TextUtils.equals("ImageBASE64", name)) {
                                requestMap.put(name, formBody.value(i));
                                dataMap.put("ImageType", "BASE64");
                            } else if (TextUtils.equals("partFileMapJson", name)) {
                                partFileMap = GsonUtils.fromLocalJson(formBody.value(i), new TypeToken<Map<String, String>>() {
                                }.getType());
                            } else {
                                dataMap.put(name, formBody.value(i));
                            }
                        }
                        /*** 添加公共参数 */
                        dataMap.putAll(getCommonParameter());
                        String dataStr = GsonUtils.toJson(dataMap);
                        requestMap.put("data", QianToonApiUtil.sm4Encrypt(timeStamp, dataStr));
                    }
                } else {
                    Buffer buffer = new Buffer();
                    request.body().writeTo(buffer);
                    String data = buffer.readUtf8();
                    Map<String,String> map = GsonUtils.fromLocalJson(data,Map.class);
                    map.putAll(getCommonParameter());

                    String dataStr = GsonUtils.toJson(map);
                    requestMap.put("data", QianToonApiUtil.sm4Encrypt(timeStamp, dataStr));
                    Log.e("====>",dataStr);
//                    requestMap.put("data", QianToonApiUtil.sm4Encrypt(timeStamp, buffer.readUtf8()));
                }
                RequestBody body;
                if (partFileMap != null && partFileMap.size() > 0) {
                    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

                    builder.addFormDataPart("inJson", GsonUtils.toJson(requestMap));
                    for (Map.Entry<String, String> entry : partFileMap.entrySet()) {
                        File file = new File(entry.getValue());
                        RequestBody fileRQ = RequestBody.create(MultipartBody.FORM, file);
                        builder.addFormDataPart(entry.getKey(), file.getName(), fileRQ);
                    }

                    body = builder.build();
                } else {
                    body = RequestBody.create(QianToonApiUtil.getDefaultMediaType(), GsonUtils.toJson(requestMap));
                }
                //重构请求
                request = request.newBuilder()
                        .headers(request.headers())
                        .post(body)
                        .build();
            }
            Response response = chain.proceed(request);
            return response;
        };
    }

    @Override
    protected Interceptor getResponseInterceptor() {
        // Debug版本，打印请求日志
        if (iNetworkRequiredInfo.isDebug()) {
            return chain -> {
                String requestTime = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
                Response response = chain.proceed(chain.request());
                String responseTime = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
                try {
                    Buffer buffer = new Buffer();
                    chain.request().body().writeTo(buffer);
                    String requestBodyStr = buffer.clone().readUtf8();
                    String responseBodyStr = response.body().source().getBuffer().clone().readUtf8();
//
//                    Log.e("requestBodyStr====>",requestBodyStr);
//                    Log.e("responseBodyStr====>",responseBodyStr+" ==>13");

                    JSONObject requestObject = new JSONObject(requestBodyStr);
                    RequestHead requestHead = new RequestHead("", "", "");
                    String head = "";
                    String requestData = "";
                    if (!TextUtils.isEmpty(getAuth_token())) {
                        head = requestObject.getString("head");
                        requestData = requestObject.getString("data");
                        requestHead = GsonUtils.fromLocalJson(head, new TypeToken<RequestHead>() {
                        }.getType());
                    }
                    BaseResponseBean responseBean = GsonUtils.fromLocalJson(responseBodyStr, new TypeToken<BaseResponseBean>() {
                    }.getType());
                    LogUtils.i(
                            "请求时间：" + requestTime +
                                    "\n 响应时间：" + responseTime +
                                    "\n 地址：" + chain.request().url() +
                                    "\n 参数head：" + head +
                                    "\n 参数data：" + GsonUtils.toJson(QianToonApiUtil.sm4Decrypt(requestHead.getTimeStamp(), requestData, Object.class)) +
                                    "\n 结果head：" + GsonUtils.toJson(responseBean.getHead()) +
                                    "\n 结果data：" + GsonUtils.toJson(responseBean.getDecryptData(Object.class))
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return response;
            };
        }
        return null;
    }

    @Override
    public String getFormal() {
        return String.format(URL, iNetworkRequiredInfo.getBaseUrl(), iNetworkRequiredInfo.getPort());
    }
}
